/**
 * 图片尺寸标准化配置
 */
export interface ImageSizeStandard {
  name: string
  description: string
  width: number
  height: number
  tolerance: number // 允许的误差范围（像素）
  category: 'ultra-hd' | 'qhd' | 'fhd' | 'hd' | 'mobile' | 'custom'
  orientation: 'landscape' | 'portrait' | 'square' // 屏幕方向
}

export interface SizeNormalizationResult {
  original: string // 原始尺寸文本
  width: number // 宽度
  height: number // 高度
  standard: ImageSizeStandard | null // 匹配的标准尺寸（如果有）
  orientation: 'landscape' | 'portrait' | 'square' // 屏幕方向
  isStandard: boolean // 是否为标准尺寸
  standardName: string // 标准尺寸名称
}

/**
 * 图片标准尺寸常量
 */
export const STANDARD_IMAGE_SIZES: Record<string, ImageSizeStandard> = {
  '4K_UHD': {
    name: '4K',
    description: '4K 超高清，主流高分辨率标准，提供出色的视觉体验',
    width: 3840,
    height: 2160,
    tolerance: 0,
    category: 'ultra-hd',
    orientation: 'landscape',
  },
  '4K_DCI': {
    name: '4K DCI',
    description: '4K 数字影院标准，专业影视制作专用格式',
    width: 4096,
    height: 2160,
    tolerance: 0,
    category: 'ultra-hd',
    orientation: 'landscape',
  },
  '4K_PORTRAIT': {
    name: '4K 手机',
    description: '4K 竖屏分辨率，适合高端手机壁纸和社交媒体内容',
    width: 2160,
    height: 3840,
    tolerance: 0,
    category: 'ultra-hd',
    orientation: 'portrait',
  },
}

/**
 * 图片处理工具类
 */
export class ImageHandler {
  private static instance: ImageHandler

  public static getInstance(): ImageHandler {
    if (!ImageHandler.instance) {
      ImageHandler.instance = new ImageHandler()
    }
    return ImageHandler.instance
  }

  /**
   * 标准化图片尺寸
   */
  public normalizeSize(sizeText: string): SizeNormalizationResult {
    const dimensions = this.extractDimensions(sizeText)
    const orientation = this.determineOrientation(dimensions.width, dimensions.height)

    const matchedStandard = this.findMatchingStandard(dimensions.width, dimensions.height, orientation)

    return {
      original: sizeText,
      standard: matchedStandard,
      width: dimensions.width,
      height: dimensions.height,
      orientation,
      isStandard: matchedStandard !== null,
      standardName: matchedStandard?.name || sizeText,
    }
  }

  /**
   * 从文本中提取尺寸信息
   */
  private extractDimensions(text: string): { width: number, height: number } {
    // 匹配各种格式：3840x2400、3840×2400、3840 * 2400、3840 * 2400px
    const patterns = [
      /(\d+)[x×*]\s*(\d+)/i, // 3840x2400
      /(\d+)\s*[x×*]\s*(\d+)/i, // 3840 x 2400
      /width\s*[:=]\s*(\d+)\D*height\s*[:=]\s*(\d+)/i, // width:3840 height:2400
      /(\d+)\s*p\s*x\s*(\d+)/i, // 3840px x 2400px
    ]

    for (const pattern of patterns) {
      const match = text.match(pattern)
      if (match) {
        const width = Number.parseInt(match[1])
        const height = Number.parseInt(match[2])
        if (width > 0 && height > 0) {
          return { width, height }
        }
      }
    }

    // 如果无法提取，返回默认值
    return { width: 0, height: 0 }
  }

  /**
   * 确定屏幕方向
   */
  private determineOrientation(width: number, height: number): 'landscape' | 'portrait' | 'square' {
    if (width === 0 || height === 0)
      return 'landscape'

    const ratio = width / height
    if (ratio > 1.1)
      return 'landscape'
    if (ratio < 0.9)
      return 'portrait'
    return 'square'
  }

  /**
   * 查找匹配的标准尺寸（考虑方向）
   */
  private findMatchingStandard(width: number, height: number, orientation: string): ImageSizeStandard | null {
    if (width === 0 || height === 0)
      return null

    // 规则1：优先检查竖屏4K（宽度小于高度）
    if (width < height) {
      const portrait4K = this.checkPortrait4K(width, height)
      if (portrait4K) {
        return portrait4K
      }
    }

    // 规则2：按方向匹配其他标准尺寸
    for (const standard of Object.values(STANDARD_IMAGE_SIZES)) {
      if (standard.orientation === orientation && this.isSizeMatch(standard, width, height)) {
        return standard
      }
    }

    // 规则3：放宽方向限制匹配
    for (const standard of Object.values(STANDARD_IMAGE_SIZES)) {
      if (this.isSizeMatch(standard, width, height)) {
        return standard
      }
    }

    return null
  }

  /**
   * 检查是否为竖屏 4K 尺寸
   */
  private checkPortrait4K(width: number, height: number): ImageSizeStandard | null {
    const portrait4K = STANDARD_IMAGE_SIZES['4K_PORTRAIT']

    // 检查是否接近 4K 竖屏标准
    if (this.isPortrait4KMatch(width, height)) {
      return portrait4K
    }

    return null
  }

  /**
   * 检查是否匹配竖屏 4K 标准
   */
  private isPortrait4KMatch(width: number, height: number): boolean {
    const portrait4K = STANDARD_IMAGE_SIZES['4K_PORTRAIT']

    // 条件1：必须是竖屏（宽度小于高度）
    if (width >= height) {
      return false
    }

    // 条件2：高度接近 4K 标准（3840像素）
    const heightMatch = Math.abs(height - portrait4K.height) <= portrait4K.tolerance

    // 条件3：宽度在合理范围内（基于比例计算）
    const expectedWidth = Math.round((width / height) * portrait4K.height)
    const widthMatch = Math.abs(width - expectedWidth) <= portrait4K.tolerance * 2 // 放宽宽度容差

    // 条件4：总像素数接近 4K 级别
    const totalPixels = width * height
    const standardPixels = portrait4K.width * portrait4K.height
    const pixelRatio = totalPixels / standardPixels
    const pixelMatch = pixelRatio >= 0.7 && pixelRatio <= 1.3 // 允许 30% 的像素差异

    return heightMatch && widthMatch && pixelMatch
  }

  /**
   * 检查尺寸是否匹配标准
   */
  private isSizeMatch(standard: ImageSizeStandard, width: number, height: number): boolean {
    const widthMatch = Math.abs(width - standard.width) <= standard.tolerance
    const heightMatch = Math.abs(height - standard.height) <= standard.tolerance

    // 检查正向匹配
    if (widthMatch && heightMatch) {
      return true
    }

    // 检查旋转匹配（宽高互换）
    const rotatedWidthMatch = Math.abs(width - standard.height) <= standard.tolerance
    const rotatedHeightMatch = Math.abs(height - standard.width) <= standard.tolerance

    return rotatedWidthMatch && rotatedHeightMatch
  }
}
